package com.link_with_health.utils;


import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;

@Component
public class RandomCodeUtil {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private Random random = new Random();
    private final String[] FONT_NAMES = {"宋体"
            , "华文楷体", "黑体"
            , "Georgia", "微软雅黑"
            , "楷体_GB2312"};
    private final Integer MAX_FONT_SIZE = 30;
    private final Integer MIN_FONT_SIZE = 20;
    private final String RANDOM_CHARACTER =
            "0123456789ABCdefghiDEFGHIJopPQR"
            + "VWXYZabcjklSTUmnqrstKLMNOvuwxyz";

    //随机字体
    private Font randomFont(){
        int index = random.nextInt(this.FONT_NAMES.length);
        String fontName = this.FONT_NAMES[index];
        int style = random.nextInt(4);
        int size = random.nextInt(MAX_FONT_SIZE
                - MIN_FONT_SIZE + 1) + MIN_FONT_SIZE;
        return new Font(fontName ,style ,size);
    }

    //随机颜色
    private Color randomColor(){
        int red = random.nextInt(225);
        int green = random.nextInt(225);
        int blue = random.nextInt(225);
        return new Color(red ,green ,blue);
    }
    //随机字符
    private Character randomChar(){
        String str = this.RANDOM_CHARACTER;
        return str.charAt(random.nextInt(str.length()));
    }

    /**
     * 获取随机验证码
     * @param num 验证码长度
     * @return 验证码
     */
    public Integer randomNum(Integer num){
        int randomNum = 0;
        for(int round = 0; round < num; round++ ){
            if(round == num-1){
                randomNum = randomNum + (random.nextInt(9)
                        +1) * (int)Math.pow(10,round);
                break;
            }
            randomNum = randomNum + (random.nextInt(10)
                ) * (int)Math.pow(10,round);
        }
        return randomNum;
    }


    /**
     * 默认四字符
     * @param output 字节流
     * @return 验证码
     */
    public String randomImage(ByteArrayOutputStream output){
        return randomImage(output,4);
    }

    /**
     * 获取验证码
     * @param output 字节流
     * @param randomNumber 随机码长度 （4-6）
     * @return
     */
    public String randomImage(ByteArrayOutputStream output,int randomNumber){
        String code = "";
        int width = 120;
        int height = 40;
        int number = randomNumber < 0 ? 4 :randomNumber;
        number = Math.min(number, 6);

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        Graphics2D graphics = image.createGraphics();
        graphics.setBackground(new Color(255,255,255,255));
        graphics.clearRect(0, 0, width, height);

        StringBuffer buffer = new StringBuffer();
        for (int round = 0; round < randomNumber; round ++){
            String charset = randomChar() + "";
            buffer.append(charset);
            //定义坐标
            float x = round * 1.0F * width / 5.0F + width/8.0F;
            graphics.setFont(randomFont());
            graphics.setColor(randomColor());
            graphics.drawString(charset, x, height / 1.5F);
        }
        code = buffer.toString();
        //干扰线
        int lineNum = random.nextInt(3) + 3;
        Graphics2D graphicsWithLine = (Graphics2D) image.getGraphics();
        for (int round = 0; round < lineNum; round++){
            int x1 = random.nextInt(width);
            int x2 = random.nextInt(width);
            int y1 = random.nextInt(height);
            int y2 = random.nextInt(height);
            graphicsWithLine.setColor(randomColor());
            graphicsWithLine.drawLine(x1, y1, x2, y2);
        }
        graphics.dispose();
        try{
            ImageIO.write(image, "jpg", output);
        } catch (IOException e){
            logger.error("Create randomImage fail",e);
        }

        return code;
    }

    public static String outStream2base64(ByteArrayOutputStream out){
        return new String(Base64.encodeBase64(out.toByteArray()));
    }


    public static void main(String[] args){
        RandomCodeUtil util = new RandomCodeUtil();
        System.out.println(util.randomNum(6));
    }
}
